package problem1372;

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode() {}
 *     TreeNode(int val) { this.val = val; }
 *     TreeNode(int val, TreeNode left, TreeNode right) {
 *         this.val = val;
 *         this.left = left;
 *         this.right = right;
 *     }
 * }
 */

//1372.二叉树中的最长交错路劲
    //https://leetcode.cn/problems/longest-zigzag-path-in-a-binary-tree/


class Solution {
    int ret;
    public int longestZigZag(TreeNode root) {
        if(root == null) return 0;
        ret = 0;
        maxlength(root, true, 0);
        maxlength(root, false, 0);
        return ret;
    }
    
    //flag == true 上一个节点遍历的是左树
    //flag == flase 上一个节点遍历的是右树
    public void maxlength(TreeNode root , boolean flag, int len) {
        if(root == null) return;
        ret = Math.max(ret, len);
        if(flag == true) {
            //遍历右字数
            maxlength(root.right, false, len+1);
            maxlength(root.left, true, 1);
        }else {
            maxlength(root.left, true, len+1);
            maxlength(root.right, false, 1);
        }
    }
}